<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.blurry" size="small" clearable placeholder="输入名称或者描述搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-date-picker
          v-model="query.createTime"
          :default-time="['00:00:00','23:59:59']"
          type="daterange"
          range-separator=":"
          size="small"
          class="date-item"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!-- 表单渲染 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="520px">
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" style="width: 380px;" />
        </el-form-item>
        <el-form-item label="角色级别" prop="adminType">
          <el-input-number v-model.number="form.adminType" :min="1" controls-position="right" style="width: 145px;" />
        </el-form-item>
        <el-form-item label="描述信息" prop="note">
          <el-input v-model="form.note" style="width: 380px;" rows="5" type="textarea" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.roleStatus">
            <el-radio
              v-for="item in enabledTypeOptions"
              :key="item.key"
              :label="item.key"
            >{{ item.display_name }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table ref="table" v-loading="crud.loading" highlight-current-row style="width: 100%;" :data="crud.data[crud.listName]" @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange">
            <el-table-column :selectable="checkboxT" type="selection" width="55" />
            <el-table-column prop="roleName" label="名称" />
            <el-table-column prop="adminType" label="角色级别" />
            <el-table-column :show-overflow-tooltip="true" prop="note" label="描述" />
            <el-table-column label="状态" align="center" prop="isfrozen">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.roleStatus === 1 ? '正常' : '禁用'" placement="top">
                  <el-switch
                    v-model="scope.row.roleStatus"
                    :active-value="1"
                    :inactive-value="2"
                    active-color="#409EFF"
                    inactive-color="#F56C6C"
                    @change="changeEnabled(scope.row, scope.row.roleStatus)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" width="135px" prop="createTime" label="创建日期">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-permission="['admin','roles/update','roles/delete']" label="操作" width="130px" align="center" fixed="right">
              <template slot-scope="scope">
                <udOperation
                  v-if="scope.row.adminType >= adminType"
                  :data="scope.row"
                  :permission="permission"
                />
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </el-card>
      </el-col>
      <!-- 菜单授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              v-permission="permission.setMenus"
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</el-button>
          </div>
          <!--          <el-tree-->
          <!--            ref="menu"-->
          <!--            lazy-->
          <!--            :data="menus"-->
          <!--            :default-checked-keys="menuIds"-->
          <!--            :load="getMenuDatas"-->
          <!--            :props="defaultProps"-->
          <!--            check-strictly-->
          <!--            accordion-->
          <!--            show-checkbox-->
          <!--            node-key="id"-->
          <!--          />-->
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            empty-text="菜单树加载中，请稍等..."
            accordion
            show-checkbox
            node-key="id"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import crudRoles from '@/api/system/role'
import { getMenusTree } from '@/api/system/menu'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

const defaultForm = { id: null, roleName: null, note: null, adminType: 3, roleStatus: 1 }
export default {
  name: 'Role',
  components: { pagination, crudOperation, rrOperation, udOperation },
  cruds() {
    return CRUD({ title: '角色', url: 'admin/role/list', sort: 'level,asc', crudMethod: { ...crudRoles }, optShow: { reset: true, add: true, edit: false, del: false, download: false }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      defaultProps: { children: 'children', label: 'title', isLeaf: 'leaf' },
      currentId: 0, menuLoading: false, showButton: false,
      menus: [], menuIds: [],
      menuTreeData: [],
      adminType: 3,
      permission: {
        add: ['admin', 'role/add'],
        edit: ['admin', 'role/update'],
        del: ['admin', 'role/delete'],
        export: ['admin', 'role/export'],
        setMenus: ['admin', 'auth/assign']
      },
      rules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        permission: [
          { required: true, message: '请输入权限', trigger: 'blur' }
        ]
      },
      enabledTypeOptions: [
        { key: 1, display_name: '正常' },
        { key: 2, display_name: '禁用' }
      ]
    }
  },
  watch: {},
  created() {
    crudRoles.getLevel({ aid: 1 }).then(data => {
      this.adminType = data.content
    })
  },
  mounted() {
    this.getMenusTree()
  },
  methods: {
    // 改变状态
    changeEnabled(data, val) {
      const displayName = val === 1 ? '启用' : '禁用'
      this.$confirm('此操作将 "' + displayName + '" ' + data.roleName + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudRoles.edit(data).then(res => {
          this.crud.notify(displayName + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.roleStatus = data.roleStatus === 2 ? 1 : 2
        })
      }).catch(() => {
        data.roleStatus = data.roleStatus === 2 ? 1 : 2
      })
    },
    checkNodes(menu, isChoose) {
      if (menu.children) {
        for (let i = 0; i < menu.children.length; i++) {
          const index = this.menuIds.indexOf(menu.children[i].id)
          if (isChoose) {
            index === -1 && this.menuIds.push(menu.children[i].id)
          } else {
            index !== -1 && this.menuIds.splice(index, 1)
          }
          this.checkNodes(menu.children[i], isChoose)
        }
      }
    },
    menuChange(menu) {
      // 判断是否在 menuIds 中，如果存在则删除，否则添加
      if (this.menuIds.indexOf(menu.id) !== -1) {
        this.menuIds.splice(this.menuIds.indexOf(menu.id), 1)
        this.checkNodes(menu, false)
      } else {
        this.menuIds.push(menu.id)
        this.checkNodes(menu, true)
      }
      this.$refs.menu.setCheckedKeys(this.menuIds)
    },
    getMenusTree() {
      getMenusTree().then(res => {
        this.menus = res.content
      })
    },
    fn(item) {
      return item.id === this.currentId
    },
    [CRUD.HOOK.afterRefresh]() {
      this.$refs.menu.setCheckedKeys([])
      const ind = this.crud.data[this.crud.listName].findIndex(this.fn)
      const i = ind >= 0 ? ind : 0
      // 保存当前的选中类目id
      this.currentId = this.crud.data[this.crud.listName][i].id
      this.setCurrent(this.crud.data[this.crud.listName][i])
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空菜单的选中
        this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.id
        this.showButton = this.adminType <= val.adminType && val.id != 1
        // 初始化
        this.menuIds = []
        // 半选菜单
        let halfMenuList = []
        // 菜单数据需要特殊处理
        if (val.halfMenuInfoList) {
          halfMenuList = val.halfMenuInfoList.map(function(data, index) {
            return data.id
          })
        }
        val.menuDTOList && val.menuDTOList.forEach(function(data, index) {
          if (!halfMenuList.includes(data.id)) {
            _this.menuIds.push(data.id)
          }
        })
      }
    },
    // 保存菜单
    saveMenu() {
      this.menuLoading = true
      const role = { id: this.currentId, menuDTOList: [], halfMenuDTOList: [] }
      // 得到半选的父节点数据，保存起来
      this.$refs.menu.getHalfCheckedNodes().forEach(function(data, index) {
        const menu = { id: data.id }
        role.halfMenuDTOList.push(menu)
      })
      // 得到已选中的 key 值
      this.$refs.menu.getCheckedKeys().forEach(function(data, index) {
        const menu = { id: data }
        role.menuDTOList.push(menu)
      })
      crudRoles.editMenu(role).then(res => {
        this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.menuLoading = false
        this.update()
        this.crud.refresh()
      }).catch(err => {
        this.menuLoading = false
        console.log(err.response)
      })
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.halfMenuInfoList && crud.form.halfMenuInfoList.length) {
        crud.form.halfMenuInfoList = crud.form.halfMenuInfoList.map(item => item.id)
      }
      return true
    },
    // 改变数据
    update() {
      // 无刷新更新 表格数据
      // crudRoles.get(this.currentId).then(res => {
      //   for (let i = 0; i < this.crud.data[crud.listName].length; i++) {
      //     if (res.data.id === this.crud.data[crud.listName][i].id) {
      //       this.crud.data[crud.listName][i] = res.data
      //       break
      //     }
      //   }
      // })
    },
    checkboxT(row, rowIndex) {
      return row.adminType >= this.adminType
    },
    // 设置选中
    setCurrent(row) {
      this.$refs.table.setCurrentRow(row)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .role-span {
    font-weight: bold;color: #303133;
    font-size: 15px;
  }
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
  /deep/ .vue-treeselect__multi-value{
    margin-bottom: 0;
  }
  /deep/ .vue-treeselect__multi-value-item{
    border: 0;
    padding: 0;
  }
</style>
